﻿Public Class SSISServices
    Implements ISSISServices
    ''' <summary>
    ''' ExecuteSSIS This function is used to execute SSIS Service
    ''' </summary>
    ''' <param name="pkgVar"> Parameter for the SSIS package E.G. Package Password, Package Filename, Parameter</param>
    ''' <returns>SSISPackageResult. E.g. Error Message...etc</returns>
    ''' <remarks></remarks>
    Public Function ExecuteSSIS(ByVal pkgVar As SSISPackage) As SSISPackageResult Implements ISSISServices.ExecuteSSIS

        Dim app As Microsoft.SqlServer.Dts.Runtime.Application
        Dim pkg As Microsoft.SqlServer.Dts.Runtime.Package
        app = New Microsoft.SqlServer.Dts.Runtime.Application()
        app.PackagePassword = pkgVar.PackagePassword


        pkg = app.LoadPackage(pkgVar.PackagePath, Nothing)
        If Not pkgVar.VariableArray Is Nothing Then
            If pkgVar.VariableArray.Count > 0 Then
                For i As Integer = 0 To pkgVar.VariableArray.Count - 1
                    pkg.Variables(pkgVar.VariableArray(i).VariableName).Value = pkgVar.VariableArray(i).VariableValue

                Next
            End If
        End If

        pkg.Execute()
        Dim result As New SSISPackageResult
        result.ExecutionResult = pkg.ExecutionResult.ToString
        result.ExecutionStatus = pkg.ExecutionStatus.ToString

        Dim ErrorArray As New List(Of SSISPackageError)


        If pkg.Errors.Count > 0 Then
            For j As Integer = 0 To pkg.Errors.Count - 1
                Dim sError As New SSISPackageError()
                sError.Description = pkg.Errors(j).Description
                sError.ErrorCode = pkg.Errors(j).ErrorCode
                sError.Source = pkg.Errors(j).Source
                sError.SubComponent = pkg.Errors(j).SubComponent
                ErrorArray.Add(sError)
            Next
        End If
        result.ErrorArray = ErrorArray

        Return result
    End Function

End Class
